from flask import Flask, request, Response, jsonify
import json

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'hello world'


@app.route('/register', methods=['POST'])
# @app.route('/register', methods=['GET', 'POST'])  ##让它同时支持GET和POST
def register():
    print(request.headers)
    # print(request.stream.read()) # 不要用，否则下面的form取不到数据
    print(request.form)
    print(request.form['name'])
    print(request.form.get('name'))
    print(request.form.getlist('name'))
    print(request.form.get('nickname', default='little apple'))
    return 'welcome'

##处理json数据
@app.route('/add', methods=['POST'])
def add():
    print(request.headers)
    print(type(request.json))
    print(request.json)
    result = {'sum': request.json['a'] + request.json['b']}
    ###响应一个json或者resp = jsonify(result);
    resp = Response(json.dumps(result), mimetype='application/json')

    ###定制http响应头
    resp.headers.add('Server', 'python flask')
    return resp


if __name__ == '__main__':
    app.run(port=5000, debug=True)